package com.changgou.core.seata;

import com.alibaba.cloud.seata.GlobalTransactionAutoConfiguration;
import com.alibaba.cloud.seata.SeataProperties;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.spring.annotation.GlobalTransactionScanner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * 自动配置类
 * @author ljh
 * @version 1.0
 * @date 2021/1/17 14:55
 * @description 标题
 * @package com.changgou.core.seata
 */
@Configuration
@ConditionalOnClass(DataSourceProxy.class)//用seata的时候
@EnableConfigurationProperties(SeataProperties.class)//启用属性映射
@AutoConfigureAfter(GlobalTransactionAutoConfiguration.class)//在seata的官方的配置完成之后再执行我自己的配置
public class SeataAutoConfiguration {

    private final ApplicationContext applicationContext;

    private final SeataProperties seataProperties;

    public SeataAutoConfiguration(ApplicationContext applicationContext, SeataProperties seataProperties) {
        this.applicationContext = applicationContext;
        this.seataProperties = seataProperties;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Primary
    @Bean("dataSourceProxy")
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        //AT模式
        return new DataSourceProxy(dataSource);
    }

    @Bean
    @Primary//优先级高
    public GlobalTransactionScanner globalTransactionScanner() {

        String applicationName = applicationContext.getEnvironment()
                .getProperty("spring.application.name");

        String txServiceGroup = seataProperties.getTxServiceGroup();

        if(!StringUtils.isEmpty(txServiceGroup) && !txServiceGroup.equals("my_test_tx_group")  ){
            txServiceGroup="my_test_tx_group";
        }
        if (StringUtils.isEmpty(txServiceGroup)) {
            //txServiceGroup = applicationName + "-fescar-service-group";
            txServiceGroup="my_test_tx_group";
            seataProperties.setTxServiceGroup(txServiceGroup);
        }
        return new GlobalTransactionScanner(applicationName, txServiceGroup);
    }
}
